package com.sfh.cp.user.pst;

import android.content.res.AssetManager;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sfh.cp.user.ReqUserInfo;
import com.sfh.cp.util.lub.Luban;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.http.service.HandleException;
import com.sfh.lib.mvp.IResult;
import com.sfh.lib.mvp.service.AbstractPresenter;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;
import crm.sfh.server.Const;
import crm.sfh.server.SUser;
import crm.sfh.server.entity.ECity;
import crm.sfh.server.entity.EDegreeType;
import crm.sfh.server.entity.EUser;
import io.reactivex.Observable;
import io.reactivex.functions.Function;

/**
 * 功能描述:
 *
 * @date 2018/5/24
 */
public class PstUserInfo extends AbstractPresenter<IPstUserInfo.IVUserInfo> implements IPstUserInfo {


    @Override
    public void getUser() {

        this.execute(0x121219, Observable.just(1).map(new Function<Integer, EUser>() {
            @Override
            public EUser apply(Integer integer) throws Exception {
                final SUser user = AppCacheManager.newInstance().getCache(Const.USER, new SUser());
                if (TextUtils.isEmpty(user.getObjectId())) {
                    return null;
                }
                return user.getUser();
            }
        }), new IResult<EUser>() {
            @Override
            public void onSuccess(EUser user) throws Exception {
                if (user != null) {
                    getView().onUserInfo(user);
                }
            }

            @Override
            public void onFail(HandleException e) {
            }
        });
    }

    @Override
    public void listCity() {
        getView().showLoading(true);
        Observable<List<ECity>> observable = Observable.just("citys.json").map(new Function<String, List<ECity>>() {
            @Override
            public List<ECity> apply(String s) throws Exception {
                String json = openFile(s);
                if (!TextUtils.isEmpty(json)) {
                    return new Gson().fromJson(json, new TypeToken<List<ECity>>() {
                    }.getType());
                }
                return new ArrayList<>(0);
            }
        });
        this.execute(0x1, observable, new IResult<List<ECity>>() {
            @Override
            public void onSuccess(List<ECity> eCities) throws Exception {
                getView().hideLoading();
                getView().onCity(eCities);
            }

            @Override
            public void onFail(HandleException e) {
                getView().hideLoading();
                getView().showToast(e.getMsg());
            }
        });
    }

    @Override
    public void updateUser(ReqUserInfo info) {
        final SUser user = AppCacheManager.newInstance().getCache(Const.USER, new SUser());
        if (TextUtils.isEmpty(user.getObjectId())) {
            return;
        }


        SUser temp = new SUser();
        temp.setObjectId(user.getObjectId());
        if (!TextUtils.isEmpty(info.getHead())) {
            updateHead(temp, info.getHead());
            return;
        }
        if (!TextUtils.isEmpty(info.getSex())) {
            temp.setSex(info.getSex());
        }
        if (!TextUtils.isEmpty(info.getAddress())) {
            temp.setAddress(info.getAddress());
        }
        if (!TextUtils.isEmpty(info.getDegreeType())) {
            temp.setDegreeType(info.getDegreeType());
        }
        if (!TextUtils.isEmpty(info.getName())) {
            temp.setName(info.getName());
        }
        this.updateUser(temp);
    }

    private void updateHead(final SUser temp, String file) {


        this.execute(0x1222, Observable.just(file).map(new Function<String, File>() {
            @Override
            public File apply(String s) throws Exception {
                File newFile = new File(AppCacheManager.newInstance().getFileCache(), temp.getObjectId() + "_" + System.currentTimeMillis() + ".jpg");
                return new Luban().leastCompressSize(200).load(s).compress(newFile);
            }
        }), new IResult<File>() {
            @Override
            public void onSuccess(File file) throws Exception {
                final BmobFile bmobFile = new BmobFile(file);
                bmobFile.upload(AppCacheManager.getApplication(), new UploadFileListener() {
                    @Override
                    public void onSuccess() {
                        temp.setUrl(bmobFile.getUrl());
                        updateUser(temp);
                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
            }

            @Override
            public void onFail(HandleException e) {
            }
        });

    }

    private void updateUser(final SUser temp) {
        temp.update(AppCacheManager.getApplication(), new UpdateListener() {
            @Override
            public void onSuccess() {
                BmobQuery<SUser> userBmobQuery = new BmobQuery<>();
                userBmobQuery.getObject(AppCacheManager.getApplication(), temp.getObjectId(), new GetListener<SUser>() {
                    @Override
                    public void onSuccess(SUser sUser) {
                        AppCacheManager.newInstance().putCache(true, Const.USER, sUser);
                    }

                    @Override
                    public void onFailure(int i, String s) {
                    }
                });
            }

            @Override
            public void onFailure(int i, String s) {
                getView().showToast(s);
            }
        });
    }

    @Override
    public void listDegreeType() {
        getView().showLoading(true);
        Observable<List<EDegreeType>> observable = Observable.just("degreeType.json").map(new Function<String, List<EDegreeType>>() {
            @Override
            public List<EDegreeType> apply(String s) throws Exception {
                String json = openFile(s);
                if (!TextUtils.isEmpty(json)) {
                    return new Gson().fromJson(json, new TypeToken<List<EDegreeType>>() {
                    }.getType());
                }
                return new ArrayList<>(0);
            }
        });
        execute(0x2, observable, new IResult<List<EDegreeType>>() {
            @Override
            public void onSuccess(List<EDegreeType> eCities) throws Exception {
                getView().hideLoading();
                getView().onDegreeType(eCities);
            }

            @Override
            public void onFail(HandleException e) {
                getView().hideLoading();
                getView().showToast(e.getMsg());
            }
        });
    }

    /***
     * 读取文件
     * @param fileName
     * @return
     */
    public static String openFile(String fileName) {
        AssetManager assetManager = AppCacheManager.getApplication().getAssets();
        StringBuffer json = new StringBuffer(2000);
        BufferedReader bufferedReader = null;
        try {
            InputStreamReader reader = new InputStreamReader(assetManager.open(fileName));
            bufferedReader = new BufferedReader(reader);
            String content;
            while (!TextUtils.isEmpty(content = bufferedReader.readLine())) {
                json.append(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                }
            }
        }
        return json.toString();
    }
}
